package com.rongc.client.freight.base.view.activity;

import android.Manifest;
import android.content.Intent;
import android.os.Environment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.error.VolleyError;
import com.rongc.client.core.exception.RegexException;
import com.rongc.client.core.network.code.HandleCode;
import com.rongc.client.core.network.http.RequestManager;
import com.rongc.client.core.utils.ActivityUtils;
import com.rongc.client.core.utils.FileUtil;
import com.rongc.client.core.utils.ImageUtils;
import com.rongc.client.core.utils.StringUtils;
import com.rongc.client.freight.R;
import com.rongc.client.freight.UniApplication;
import com.rongc.client.freight.base.BaseActivity;
import com.rongc.client.freight.base.model.BaseDic;
import com.rongc.client.freight.base.request.api.DriverVerifyApi;
import com.rongc.client.freight.base.request.api.ShipperVerifyApi;
import com.rongc.client.freight.base.request.result.NullResult;
import com.rongc.client.freight.base.view.adapter.RecyclerAuthAdapter;
import com.rongc.client.freight.base.view.adapter.RecyclerBaseAdapter;
import com.rongc.client.freight.business.mine.view.activity.ProblemActivity;
import com.rongc.client.freight.utils.UtilMethod;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import cn.bingoogolapple.photopicker.activity.BGAPhotoPickerActivity;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * Created by ccqx on 2017/6/28.
 */

public class AuthActivity extends BaseActivity implements EasyPermissions.PermissionCallbacks, View.OnClickListener{
    @Bind(R.id.recycler)
    RecyclerView mRecyclerView;

    RecyclerAuthAdapter authAdapter;
    List<HashMap<String,String>> datas;
    private ArrayList<String> netPhotos = new ArrayList<>();
    List<String> filenames = new ArrayList<>();


    private static final int REQUEST_CODE_PERMISSION_PHOTO_PICKER = 1;

    @OnClick({R.id.btn_sub,R.id.tv_protocol})
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_sub:
                // TODO
                try {
                    switch (UniApplication.getInstance().getType()) {
                        case BaseDic.IdentityType.OWNER_TYPE:
                            netPhotos.clear();
                            filenames.clear();
                            netPhotos.add(datas.get(0).get("image"));
                            filenames.add(datas.get(0).get("filename"));
                            if(StringUtils.isNotEmpty(datas.get(1).get("image"))){
                                netPhotos.add(datas.get(1).get("image"));
                                filenames.add(datas.get(1).get("filename"));
                            }

                            break;
                        case BaseDic.IdentityType.DRIVING_TYPE:
                            netPhotos.clear();
                            filenames.clear();
                            netPhotos.add(datas.get(0).get("image"));
                            netPhotos.add(datas.get(1).get("image"));
                            netPhotos.add(datas.get(2).get("image"));
                            filenames.add(datas.get(0).get("filename"));
                            filenames.add(datas.get(1).get("filename"));
                            filenames.add(datas.get(2).get("filename"));
                            break;
                    }
                    prepare();
                    doUpload();
                }catch (RegexException e){
                    ActivityUtils.toast(e.getMessage());
                }

                break;
            case R.id.tv_protocol:
                ActivityUtils.startActivity(this, ProblemActivity.class);
                break;

        }
    }

    void prepare() throws RegexException {
        for (String path :netPhotos) {
            if(StringUtils.isEmpty(path))
                throw new RegexException("请上传所有图片");
        }
    }

    private void doUpload(){
        ActivityUtils.toast("图片处理中...");
        mRecyclerView.postDelayed(new Runnable() {
            @Override
            public void run() {
                List<File> files = ImageUtils.makePaths2ImgFileList(netPhotos);
                netPhotos.clear();
                UtilMethod.showProgressDialog(AuthActivity.this, "正在上传...");
                switch (UniApplication.getInstance().getType()) {
                    case BaseDic.IdentityType.OWNER_TYPE:
                        ShipperVerifyApi p = new ShipperVerifyApi(respWorkersListener, errorListener, filenames, files,
                                new ShipperVerifyApi.ShipperVerifyParams(UniApplication.getInstance().getUserInfo().getUserId()));
                        RequestManager.getInstance().call(p);
                        break;
                    case BaseDic.IdentityType.DRIVING_TYPE:
                        DriverVerifyApi d = new DriverVerifyApi(respWorkersListener, errorListener, filenames, files,
                                new DriverVerifyApi.DriverVerifyParams(UniApplication.getInstance().getUserInfo().getUserId()));
                        RequestManager.getInstance().call(d);
                        break;
                }
            }
        },100);
    }

    Response.Listener<NullResult> respWorkersListener = new Response.Listener<NullResult>() {

        @Override
        public void onResponse(NullResult response) {
            if (HandleCode.requestSuccess()) {
                ActivityUtils.toast(HandleCode.headerMessage);
                FileUtil.clearDir(FileUtil.getTempFile());
                finish();
            } else {
                UtilMethod.dismissProgressDialog(AuthActivity.this);
            }
        }
    };


    Response.ErrorListener errorListener = new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            UtilMethod.dismissProgressDialog(AuthActivity.this);
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == StringUtils.parseInt(BaseDic.AuthType.IDCARD_TYPE)) {
            String path = BGAPhotoPickerActivity.getSelectedImages(data).get(0);
            datas.get(0).put("image",path);
        }else if (resultCode == RESULT_OK && requestCode == StringUtils.parseInt(BaseDic.AuthType.DRIVING_TYPE)) {
            String path = BGAPhotoPickerActivity.getSelectedImages(data).get(0);
            datas.get(1).put("image",path);
        }else if (resultCode == RESULT_OK && requestCode == StringUtils.parseInt(BaseDic.AuthType.YYZZ_TYPE)) {
            String path = BGAPhotoPickerActivity.getSelectedImages(data).get(0);
            datas.get(1).put("image",path);
        }else if (resultCode == RESULT_OK && requestCode == StringUtils.parseInt(BaseDic.AuthType.GROUP_TYPE)) {
            String path = BGAPhotoPickerActivity.getSelectedImages(data).get(0);
            datas.get(2).put("image",path);
        }

        authAdapter.notifyDataSetChanged();
    }

    @Override
    public void initView() {
        datas= new ArrayList<>();
        switch (UniApplication.getInstance().getType()){
            case BaseDic.IdentityType.OWNER_TYPE:
                initToolbar("货主认证");
                HashMap<String,String> data = new HashMap<>();
                data.put("name","身份证照片");  // 身份证
                data.put("id", BaseDic.AuthType.IDCARD_TYPE);
                data.put("filename", "idcard");
                data.put("image","");
                datas.add(data);
                data = new HashMap<>();
                data.put("name","营业执照（可不填）");  // 营业执照
                data.put("id",BaseDic.AuthType.YYZZ_TYPE);
                data.put("filename", "businessLicense");
                data.put("image","");
                datas.add(data);
                break;
            case BaseDic.IdentityType.DRIVING_TYPE:
                initToolbar("司机认证");
                data = new HashMap<>();
                data.put("name","身份证照片");  // 身份证
                data.put("id", BaseDic.AuthType.IDCARD_TYPE);
                data.put("filename", "idcard");
                data.put("image","");
                datas.add(data);
                data = new HashMap<>();
                data.put("name","驾驶证照片");  // 驾照
                data.put("id",BaseDic.AuthType.DRIVING_TYPE);
                data.put("filename", "driverLicense");
                data.put("image","");
                datas.add(data);
                data = new HashMap<>();
                data.put("name","本人和身份证合影");  // 合影
                data.put("id",BaseDic.AuthType.GROUP_TYPE);
                data.put("filename", "holdingPhoto");
                data.put("image","");
                datas.add(data);
                break;
        }

        authAdapter = new RecyclerAuthAdapter(this,datas);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.setAdapter(authAdapter);

        authAdapter.setOnItemClickListener(new RecyclerBaseAdapter.OnItemClickListener<HashMap<String, String>>() {
            @Override
            public void onItemClick(View view, int position, HashMap<String, String> data) {
                req = StringUtils.parseInt(data.get("id"));
                choicePhotoWrapper();
            }
        });
    }
    int req ;
    @Override
    public int getLayoutId() {
        return R.layout.activity_sys_auth;
    }

    @AfterPermissionGranted(REQUEST_CODE_PERMISSION_PHOTO_PICKER)
    private void choicePhotoWrapper() {
        String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
        if (EasyPermissions.hasPermissions(this, perms)) {
            // 拍照后照片的存放目录，改成你自己拍照后要存放照片的目录。如果不传递该参数的话就没有拍照功能
            File takePhotoDir = new File(Environment.getExternalStorageDirectory(), "FreDownload");

            startActivityForResult(BGAPhotoPickerActivity.newIntent(this, takePhotoDir, 1, null), req);
        } else {
            EasyPermissions.requestPermissions(this, "图片选择需要以下权限:\n\n1.访问设备上的照片", REQUEST_CODE_PERMISSION_PHOTO_PICKER, perms);
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        if (requestCode == REQUEST_CODE_PERMISSION_PHOTO_PICKER) {
            Toast.makeText(this, "您拒绝了「图片选择」所需要的相关权限!", Toast.LENGTH_SHORT).show();
        }
    }
}
